#!/bin/bash
# create_lib.sh
# 获取当前脚本所在的绝对路径
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)

# 引用 common_utils.sh
source "$SCRIPT_DIR/common_utils.sh"
echo "SCRIPT_DIR: $SCRIPT_DIR"  
# 定义默认值
DEFAULT_PACK_WAY="zip"
DEFAULT_CONANFILE_SOURCE="$SCRIPT_DIR/templates/source_install.py"
DEFAULT_CONANFILE_ZIP="$SCRIPT_DIR/templates/zip_download.py"
DEFAULT_SRC=""

DEFAULT_HOST_PROFILE="profiles_Ubuntu_20.04"
DEFAULT_ACTION="create"
DEFAULT_LIB_NAME="lib_name"
DEFAULT_LIB_VERSION="0.0.1"


# 帮助信息函数
show_help() {
    echo "Usage: $0 [pack_way] [src] [lib_name] [lib_version] [host_profile]"
    echo "***** pack_way: zip (default) | source"
    echo "***** src: Source directory or URL (depending on pack_way)"
    echo "***** lib_name: Name of the library"
    echo "***** lib_version: Version of the library"
    echo "***** host_profile: Build profile, default is 'profiles_Ubuntu_20.04'"
    echo "***** --help, -h: Show this help message"
}

# 检查 --help 或 -h 参数
if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
    show_help
    exit -1
fi


# 根据第一个参数设置 CONANFILE
PACK_WAY=${1:-$DEFAULT_PACK_WAY}
# 设置 SRC 和 HOST_PROFILE
SRC=${2:-$DEFAULT_SRC}
LIB_NAME=${3:-$DEFAULT_LIB_NAME}
LIB_VERSION=${4:-$DEFAULT_LIB_VERSION}
HOST_PROFILE=${5:-$DEFAULT_HOST_PROFILE}
# 如果 没设置 库名和版本号即为默认值,则提醒输入
if [ "$LIB_NAME" == "$DEFAULT_LIB_NAME" ] || [ "$LIB_VERSION" == "$DEFAULT_LIB_VERSION" ]; then
    echo "Error: Please provide a library name and version number."
fi
case "$PACK_WAY" in
    zip|z)
        CONANFILE=$DEFAULT_CONANFILE_ZIP
        update_zip_url "$SRC" "$CONANFILE" "$LIB_NAME" "$LIB_VERSION"
        ;;
    source|s)
        CONANFILE=$DEFAULT_CONANFILE_SOURCE
        # 将 SRC 转换为绝对路径
        if [[ -n "$SRC" ]]; then
            SRC=$(realpath "$SRC")
        fi
        #打印
        echo "SRC: $SRC"
        update_paths "$SRC" "$CONANFILE" "$LIB_NAME" "$LIB_VERSION"
        ;;
    *)
        echo "Error: Unknown pack way: $PACK_WAY"
        exit 1
        ;;
esac

ALL_LIB="${LIB_NAME}/${LIB_VERSION}"
INSTALL_LIB_SCRIPT="$SCRIPT_DIR/install_lib.sh"
echo "ALL_LIB: $ALL_LIB"    
echo "INSTALL_LIB_SCRIPT: $INSTALL_LIB_SCRIPT"
# 替换 install_lib.sh 中的 DEFAULT_LIB_NAME
sed -i "s|DEFAULT_LIB_NAME=\"[^\"]*\"|DEFAULT_LIB_NAME=\"${ALL_LIB}\"|" "$INSTALL_LIB_SCRIPT"


# 调用 run_build 函数
run_build "$HOST_PROFILE" "$DEFAULT_ACTION" "$CONANFILE"
